package com.example.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * @Description
 * @Date 2021/7/24
 * @Created by Jonathan
 */
@Slf4j
public class CasLock {

     AtomicInteger state = new AtomicInteger(0);

    public  void lock() {
        log.info("before lock");
        while (!state.compareAndSet(0, 1)) {
            Thread.yield();
        }
        log.info("locked");
    }

    public  void unLock() {
        log.info("before unLock");
        while (!state.compareAndSet(1, 0)) {
            Thread.yield();
        }
        log.info("unlocked");
    }

    public static void main(String[] args) {
        CasLock lock = new CasLock();
        new Thread(() -> {
            lock.lock();
            log.info("hello world");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unLock();
        }, "t1").start();
        new Thread(() -> {
            lock.lock();
            log.info("hello world");
            lock.unLock();
        }, "t2").start();
    }
}
